﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PADWH35
{
    public partial class MaintainRequestDialog : Form
    {
        Boolean isSlipJump = true;
        int AutoScorllInterval;
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case 5:
                    datagv.Location = new Point(0, datagv.Top);
                    datagv.Size = new Size(panel1.Width, panel1.Height - datagv.Top);
                    dataGridView1.Location = new Point(0, label1.Height);
                    dataGridView1.Size = new Size(this.ClientSize.Width, dataGridView1.ColumnHeadersHeight);
                    break;
            }
            base.WndProc(ref m);
        }

        public MaintainRequestDialog()
        {
            InitializeComponent();
            this.Font = new Font(this.Font.Name, 12);
            IniHelper.SetIniPath(Application.StartupPath + @"\PADWH35.ini");
            string ASI = IniHelper.IniReadValue("MaintainRequestDialog", "AutoScorllInterval");
            if (ASI == "") { ASI = "60000"; }
            SetMenuCheck("@" + ASI, false);
            datagv.AutoGenerateColumns = false;
            dataGridView1.Dock = DockStyle.Top; dataGridView1.Height = datagv.ColumnHeadersHeight;
            ColWidth(false);
        }

        Boolean isVerticalScrollBottom = true;
        int iStep = 0;
        int iSleep = Environment.TickCount;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (datagv.DisplayedRowCount(false) == datagv.RowCount || isVerticalScrollBottom)//如果datagv的数据不满一屏(没有竖直滚动条) 或 竖直滚动条到底
            {                                                                                //则刷新数据
                if (Environment.TickCount - iSleep > AutoScorllInterval || datagv.Rows.Count == 0)
                {
                    timer1.Enabled = false;
                    if (isSlipJump) { CopyGridFormat(); }
                    BindData();
                    timer1.Enabled = true;
                    isVerticalScrollBottom = false;
                    iSleep = Environment.TickCount;
                }
            }
            else
            {
                if (!isSlipJump)
                {
                    //datagv.FirstDisplayedScrollingRowIndex    设置/获取当前屏幕显示的第一行
                    //datagv.DisplayedRowCount(false)           返回向用户显示的行数
                    if (Environment.TickCount - iSleep > AutoScorllInterval)
                    {
                        datagv.FirstDisplayedScrollingRowIndex = datagv.FirstDisplayedScrollingRowIndex + datagv.DisplayedRowCount(false);
                        iSleep = Environment.TickCount;
                    }
                }
                else
                {
                    switch (iStep)
                    {
                        case 0:
                            if (Environment.TickCount - iSleep > AutoScorllInterval)
                            {
                                iStep++;
                            }
                            break;
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                            datagv.Top -= (int)((double)datagv.RowTemplate.Height * 0.05);
                            datagv.Height = panel1.Height - datagv.Top;
                            iStep++;
                            break;
                        case 21:
                            //pictureBox1.Size = this.ClientSize;
                            //pictureBox1.Image = GetScreenCapture();
                            //pictureBox1.Visible = true;
                            Application.DoEvents();
                            iStep++;
                            break;
                        case 22:
                            datagv.Top = 0;
                            datagv.FirstDisplayedScrollingRowIndex++;
                            datagv.Height = panel1.Height;
                            iStep++;
                            break;
                        case 23:
                            pictureBox1.Visible = false;
                            iSleep = Environment.TickCount;
                            iStep = 0;
                            break;
                    }
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            label2.Text = "当前时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //ColWidth(true);
        }

        private void dataGridView1_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            datagv.Columns[e.Column.Name].Width = e.Column.Width;
        }

        private void datagv_Scroll(object sender, ScrollEventArgs e)
        {

            if (e.ScrollOrientation == ScrollOrientation.VerticalScroll)
            {
                if (e.NewValue + datagv.DisplayedRowCount(false) == datagv.RowCount)
                {
                    isVerticalScrollBottom = true;
                }
                label3.Text = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString() + "/" + (datagv.RowCount / datagv.DisplayedRowCount(false) + (datagv.RowCount % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
                label3.Tag = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
            }
            else
            {
                if (isSlipJump)
                {
                    dataGridView1.FirstDisplayedScrollingColumnIndex = datagv.FirstDisplayedScrollingColumnIndex;
                    //dataGridView1.VerticalScrollingOffset = datagv.VerticalScrollingOffset;
                }
            }
        }

        private void mnuRefresh_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            BindData();
            timer1.Enabled = true;
        }

        private void mnuAutoScoll_Click(object sender, EventArgs e)
        {
            timer1.Enabled = !timer1.Enabled;
            this.mnuAutoScoll.CheckState = timer1.Enabled ? CheckState.Checked : CheckState.Unchecked;
            this.mnuScollInterval.Enabled = timer1.Enabled;
        }

        private void mnuXSecond_Click(object sender, EventArgs e)
        {
            SetMenuCheck(sender.ToString(), true);
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void BindData()
        {
            try
            {
                string sql = string.Empty;
                sql = "SELECT M.ReqID ,D.Description AS JCDept,M.ShortChar02 ," + Environment.NewLine +
                      "    'RequestDt' = CONVERT(CHAR(11), M.RequestDt, 120) + RIGHT('00' + CAST(M.RequestTime / 3600 AS VARCHAR), 2) + ':' + RIGHT('00' + CAST((M.RequestTime % 3600) / 60 AS VARCHAR), 2) ," + Environment.NewLine +
                      "    'RequiredDate' = CONVERT(CHAR(11), M.RequiredDate, 120) + RIGHT('00' + CAST(CAST(M.Number01 AS INT) / 3600 AS VARCHAR), 2) + ':' + RIGHT('00' + CAST((CAST(M.Number01 AS INT) % 3600) / 60 AS VARCHAR), 2) ," + Environment.NewLine +
                      "    'ReqStatus' = CASE M.ReqStatus WHEN 'Aprv' THEN N'批核' WHEN 'Can' THEN N'取消' WHEN 'Cmp' THEN N'完成' WHEN 'Pnd' THEN N'待定' WHEN 'Rej' THEN N'拒绝' ELSE '' END ," + Environment.NewLine +
                      "    'EquipID' = UPPER(M.EquipID) ,E.Description ,E.LocID ,M.ShortChar04 ,M.ShortChar05,M.IssueDesc ,J.JobNum ," + Environment.NewLine +
                      "    'JobStatus' = CASE WHEN L.JobNum IS NOT NULL THEN N'已报工' ELSE CASE WHEN J.JobReleased = 1 THEN N'已发放' ELSE '' END END," + Environment.NewLine +
                      "    'LineColor' = CASE WHEN J.JobNum IS NULL THEN" + Environment.NewLine +
                      "                        'W'" + Environment.NewLine +
                      "                    ELSE" + Environment.NewLine +
                      "                        CASE WHEN CONVERT(CHAR(11) , ISNULL(M.RequiredDate, '1900-01-01'), 120) +RIGHT('00' + CAST(CAST(M.Number01 AS INT) / 3600 AS VARCHAR), 2) + ':' + RIGHT('00' + CAST((CAST(M.Number01 AS INT) % 3600) / 60 AS VARCHAR), 2) < GETDATE() THEN" + Environment.NewLine +
                      "                             CASE WHEN L.JobNum IS NOT NULL THEN" + Environment.NewLine +
                      "                                'G'--超期且已报工" + Environment.NewLine +
                      "                            ELSE" + Environment.NewLine +
                      "                                'R'--超期并未报工" + Environment.NewLine +
                      "                            END" + Environment.NewLine +
                      "                        ELSE" + Environment.NewLine +
                      "                            CASE WHEN L.JobNum IS NOT NULL THEN" + Environment.NewLine +
                      "                                'G'--期限内且已报工" + Environment.NewLine +
                      "                            ELSE" + Environment.NewLine +
                      "                                'Y'--期限内并未报工" + Environment.NewLine +
                      "                            END" + Environment.NewLine +
                      "                        END" + Environment.NewLine +
                      "                    END" + Environment.NewLine +
                      "/*" + Environment.NewLine +
                      "If 无工单" + Environment.NewLine +
                      "    White" + Environment.NewLine +
                      "Else" + Environment.NewLine +
                      "    If 超期" + Environment.NewLine +
                      "        If 已报工" + Environment.NewLine +
                      "            Green" + Environment.NewLine +
                      "        Else" + Environment.NewLine +
                      "            Red" + Environment.NewLine +
                      "        End If" + Environment.NewLine +
                      "    Else" + Environment.NewLine +
                      "        If 已报工" + Environment.NewLine +
                      "            Green" + Environment.NewLine +
                      "        Else" + Environment.NewLine +
                      "            Yellow" + Environment.NewLine +
                      "        End If" + Environment.NewLine +
                      "    End If" + Environment.NewLine +
                      "End If" + Environment.NewLine +
                      "*/" + Environment.NewLine +
                      "FROM MaintReq M" + Environment.NewLine +
                      "    LEFT JOIN JobHead J ON M.Company = J.Company AND M.JobNum = J.JobNum" + Environment.NewLine +
                      "    LEFT JOIN Equip E ON M.Company = E.Company AND M.EquipID = E.EquipID" + Environment.NewLine +
                      "    LEFT JOIN JCDept D ON M.Company = D.Company AND M.ShortChar01 = D.JCDept" + Environment.NewLine +
                      "    LEFT JOIN (SELECT DISTINCT Company, JobNum FROM LaborDtl) L ON M.Company = L.Company AND M.JobNum = L.JobNum" + Environment.NewLine +
                      "WHERE M.Company = 'NSZ'" + Environment.NewLine +
                      "    AND(J.JobNum IS NULL OR J.JobComplete = 0)--未转工单或工单未结" + Environment.NewLine +
                      "    AND M.RequestDt > '2018-01-01' AND M.ReqStatus <> 'Can'" + Environment.NewLine +
                      "ORDER BY M.RequestDt DESC, M.RequestTime DESC";

                Clipboard.Clear();
                Clipboard.SetText(sql);
                DataTable dt = DBHelper.ExecuteDt(sql);
                datagv.DataSource = dt;

                //最后一页的行数不能达到一屏,补充差的行
                if (datagv.RowCount != datagv.DisplayedRowCount(false))
                {
                    int LessRow = datagv.DisplayedRowCount(false) - datagv.RowCount % datagv.DisplayedRowCount(false);
                    for (int j = 1; j <= LessRow; j++)
                    {
                        dt.Rows.Add();
                    }
                }
                //显示(当前页/总页数)
                label3.Text = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString() + "/" + (datagv.RowCount / datagv.DisplayedRowCount(false) + (datagv.RowCount % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
                label3.Tag = ((datagv.FirstDisplayedScrollingRowIndex + 1) / datagv.DisplayedRowCount(false) + ((datagv.FirstDisplayedScrollingRowIndex + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();

                //间隔双色显示
                Color color;
                for (int i = 0; i < datagv.Rows.Count; i++)
                {
                    switch (datagv[LineColorCol.Index, i].Value.ToString())
                    {
                        case "R":
                            color = Color.Red;
                            break;
                        case "G":
                            color = Color.Green;
                            break;
                        case "B":
                            color = Color.Blue;
                            break;
                        case "Y":
                            color = Color.Yellow;
                            break;
                        case "W":
                            color = Color.White;
                            break;
                        default:
                            color = datagv.GridColor;//补充的差行用表格线颜色填充背景
                            break;
                    }
                    for (int j = 0; j < datagv.Columns.Count; j++)
                    {
                        datagv.Rows[i].Cells[j].Style.BackColor = color;
                    }
                    //页数
                    if (datagv.Rows[i].Cells[ReqIDCol.Index].Value.ToString() != "")
                    {
                        datagv.Rows[i].Cells[PageCol.Index].Value = ((i + 1) / datagv.DisplayedRowCount(false) + ((i + 1) % datagv.DisplayedRowCount(false) == 0 ? 0 : 1)).ToString();
                    }
                }
            }
            catch (Exception)
            {
                //throw;
            }
        }

        private void CopyGridFormat()
        {
            dataGridView1.Visible = true;
            dataGridView1.Columns.Clear();
            foreach (DataGridViewColumn col in datagv.Columns)
            {
                dataGridView1.Columns.Add(col.Name, col.HeaderText);
                dataGridView1.Columns[col.Name].Width = col.Width;
                dataGridView1.Columns[col.Name].Visible = col.Visible;
                dataGridView1.Columns[col.Name].DefaultCellStyle = col.DefaultCellStyle;
            }
        }

        private void SetMenuCheck(string Parameter1, Boolean Parameter1_textTRUE_tagFALSE)
        {
            ToolStripMenuItem mnu = (ToolStripMenuItem)contextMenuStrip1.Items["mnuScollInterval"];
            for (int i = 0; i < mnu.DropDownItems.Count; i++)   //循环mnuScollInterval下层所有菜单项
            {
                if (mnu.DropDownItems[i] is ToolStripMenuItem)  //如果是菜单项
                {
                    if ((string)(Parameter1_textTRUE_tagFALSE ? mnu.DropDownItems[i].Text : mnu.DropDownItems[i].Tag) == Parameter1)
                    {
                        ((ToolStripMenuItem)mnu.DropDownItems[i]).Checked = true;
                        AutoScorllInterval = int.Parse(mnu.DropDownItems[i].Tag.ToString().Substring(1));
                        IniHelper.IniWriteValue("MaintainRequestDialog", "AutoScorllInterval", mnu.DropDownItems[i].Tag.ToString().Substring(1));
                    }
                    else
                    {
                        ((ToolStripMenuItem)mnu.DropDownItems[i]).Checked = false;
                    }
                }
            }
        }

        private Bitmap GetScreenCapture()//截图
        {
            Rectangle tScreenRect = new Rectangle(0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Bitmap tSrcBmp = new Bitmap(tScreenRect.Width, tScreenRect.Height); // 用于屏幕原始图片保存
            Graphics gp = Graphics.FromImage(tSrcBmp);
            gp.CopyFromScreen(0, 0, 0, 0, tScreenRect.Size);
            gp.DrawImage(tSrcBmp, 0, 0, tScreenRect, GraphicsUnit.Pixel);
            return tSrcBmp;
        }

        public void ColWidth(Boolean IsGetOrSet)
        {
            if (IsGetOrSet)
            {
                string ClipText = string.Empty;
                for (int i = 0; i < datagv.Rows[0].Cells.Count; i++)
                {
                    ClipText += "datagv.Columns[@" + datagv.Columns[i].Name + "@].Width = " + datagv.Columns[i].Width + ";\t//" + datagv.Columns[i].HeaderText + Environment.NewLine;
                }

                Clipboard.Clear();
                Clipboard.SetText(ClipText);
            }
            else
            {
                datagv.Columns["PageCol"].Width = 30;           //页
                datagv.Columns["ReqIDCol"].Width = 120;         //请求单号
                datagv.Columns["JCDeptCol"].Width = 90;         //请求部门
                datagv.Columns["ShortChar02Col"].Width = 60;    //申请人
                datagv.Columns["RequestDtCol"].Width = 145;     //开单时间
                datagv.Columns["RequiredDateCol"].Width = 145;  //预期完成时间
                datagv.Columns["ReqStatusCol"].Width = 55;      //请求状态
                datagv.Columns["EquipIDCol"].Width = 65;        //设备ID
                datagv.Columns["DescriptionCol"].Width = 155;   //描述
                datagv.Columns["LocIDCol"].Width = 60;          //位置
                datagv.Columns["ShortChar04Col"].Width = 70;    //维修单号
                datagv.Columns["IssueDescCol"].Width = 230;     //问题描述
                datagv.Columns["接单人"].Width = 60;    //申请人
                datagv.Columns["JobNumCol"].Width = 70;         //维护工单号

                if (Screen.PrimaryScreen.WorkingArea.Width - 1145 - 25 > 0)
                {
                    datagv.Columns["IssueDescCol"].Width = Screen.PrimaryScreen.WorkingArea.Width - 1145 - 25;     //问题描述
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Convert.ToInt32(label3.Tag) != 1)
            {
                datagv.FirstDisplayedScrollingRowIndex = (Convert.ToInt32(label3.Tag) - 2) * datagv.DisplayedRowCount(false);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if ((Convert.ToInt32(label3.Tag) + 0) * datagv.DisplayedRowCount(false) < datagv.Rows.Count)
            {
                datagv.FirstDisplayedScrollingRowIndex = (Convert.ToInt32(label3.Tag) + 0) * datagv.DisplayedRowCount(false);
            }
        }
    }
}
